package cn.yougou.serviceImpl;

import cn.yougou.common.CalculateUtil;
import cn.yougou.common.ListSort;
import cn.yougou.mapper.YgCommentMapper;
import cn.yougou.mapper.YgOrderMapper;
import cn.yougou.mapper.YgUserMapper;
import cn.yougou.pojo.YgComment;
import cn.yougou.pojo.YgOrder;
import cn.yougou.pojo.YgUser;
import cn.yougou.service.shopcart.YgCommentService;
import cn.yougou.vo.YgCommentVo;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (YgComment)表服务实现类
 *
 * @author 白杰崇
 * @since 2020-12-13 10:50:15
 */
@Service
public class YgCommentServiceImpl implements YgCommentService {

    @Autowired
    private YgCommentMapper ygCommentMapper;

    @Autowired
    private YgUserMapper ygUserMapper;

    @Autowired
    private YgOrderMapper ygOrderMapper;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    /**
     * 查询商品全部评论
     * @param
     * @return
     */
    @Override
    public List<YgCommentVo> getCommentAll(YgOrder ygOrder) {
        //1 首先获取到该商品下评论过的订单
        List<YgOrder> orderList = ygOrderMapper.likeComment(ygOrder);
        //2 用订单中的commentId查询出评论内容
        List<YgComment> commentList = ygCommentMapper.queryById(
                orderList,
                orderList.get(0).getCommodityid()
        );
        //3 用订单中的userId获取到用户的头像以及昵称
        List<YgUser> ygUserList = new ArrayList<>();
        System.out.println("订单内容：");
        for (YgOrder order : orderList) {
            YgUser ygUser = ygUserMapper.queryByListId(order.getUserid());
            ygUserList.add(ygUser);
        }
        //4 拼接orderList,commentList,userList得到完整的评论信息VO
        YgCommentVo ygCommentVo = null;
        //5 用于存储数据的Vo对象
        List<YgCommentVo> commentListVo = new ArrayList<> ();
        for(int i = 0; i < orderList.size(); i++){
            //判断Integer对象用equalse
            if(orderList.get(i).getCommentid().equals(commentList.get(i).getId())
                && orderList.get(i).getUserid().equals(commentList.get(i).getUserid())){
                ygCommentVo = new YgCommentVo(
                        commentList.get(i).getId(), //评论id
                        commentList.get(i).getCommodityid(),
                        ygUserList.get(i).getUserAvatar(), //用户头像
                        ygUserList.get(i).getUserid(),     //用户昵称
                        commentList.get(i).getContent(),   //评论内容
                        commentList.get(i).getHaspicture(),//是否有图片
                        commentList.get(i).getPicurls(),   //图片JSON
                        commentList.get(i).getStar(),      //评分
                        sdf.format(commentList.get(i).getAddtime()), //评价发表日期
                        orderList.get(i).getPurchsetype()   //商品规格组合值
                );
                commentListVo.add(ygCommentVo);
            }
        }
        for (YgCommentVo yg :commentListVo) {
            System.out.println(yg);
        }
        //List集合根据时间排序,纯属玩一下
        return ListSort.ListSort(commentListVo);
    }


    /**
     * 根据商品Id查询该商品 时间最新的评论
     * @param commodityid
     * @return
     */
    @Override
    public YgCommentVo commentNew(Integer commodityid){
        //1 获取到时间最新一条的评论
        YgComment ygComment = ygCommentMapper.commentNew(commodityid);
        if(ygComment != null){
            //2 拿着评论表的id去查订单表的商品规格
            YgOrder order = new YgOrder();
            order.setCommentid(ygComment.getId());
            YgOrder ygOrder = ygOrderMapper.queryCondition(order).get(0);
            //3 拿着评论表的userid去查用户表的用户头像昵称
            YgUser user = new YgUser(ygComment.getUserid());
            YgUser ygUser = ygUserMapper.queryAll(user).get(0);
            //4 拼接YgCommentVo
            YgCommentVo ygCommentVo = new YgCommentVo(
                    ygComment.getId(),
                    ygComment.getCommodityid(),
                    ygUser.getUserAvatar(),
                    ygUser.getUserid(),
                    ygComment.getContent(),
                    ygComment.getHaspicture(),
                    ygComment.getPicurls(),
                    ygComment.getStar(),
                    sdf.format(ygComment.getAddtime()),
                    ygOrder.getPurchsetype(),
                    countAll(commodityid), //总条数
                    goodReputation(commodityid) //好评率
            );
            return ygCommentVo;
        }
        return null;
    }

    /**
     * 总条数
     * @param commodityid
     * @return
     */
    @Override
    public int countAll(Integer commodityid) {
        int countAll = ygCommentMapper.countAll(commodityid);
        return countAll;
    }

    /**
     * 计算好评率
     * @param commodityid
     * @return
     */
    @Override
    public String goodReputation(Integer commodityid) {
        YgComment ygComment = new YgComment(commodityid);
        List<YgComment> commentList = ygCommentMapper.queryAll(ygComment);
        //得到好评的条数
        double goods = 0;
        for (YgComment ygComments : commentList) {
            if(ygComments.getStar() <= 5 && ygComments.getStar() > 3){
                goods++;
            }
        }
        //得到总条数
        int countAll = countAll(commodityid);
        //调用工具类
        return CalculateUtil.getPercent(goods,countAll);
    }

    /**
     * 发表评论
     * @param ygCommentVo
     * @return
     */
    @Override
    public int insComment(YgCommentVo ygCommentVo) {
        StringBuffer urlJson = new StringBuffer();
        //1 处理前端传过来的图片外网地址，不为0说明用户上传了图片
        if(ygCommentVo.getHaspicture() != 0){
            //操作字符串玩一玩,不想用fastJson
            for (String str : ygCommentVo.getUrlAft()) {
                urlJson.append('"' + str + '"' +",");
            }
            //2 拼接为josn类型的字符串存入数据库
            urlJson.insert(0,"[");
            urlJson.deleteCharAt(urlJson.length() - 1);
            urlJson.insert(urlJson.length(),"]");
            //3 将字符串存入ygCommentVo
            ygCommentVo.setPicurls(urlJson.toString());
        }
        //4 将数据复制到数据库实体类，用作插入
        YgComment ygComment = new YgComment(
                ygCommentVo.getCommodityid(),//商品id
                ygCommentVo.getType(),       //评价类型
                ygCommentVo.getContent(),    //评价内容
                ygCommentVo.getUserStaid(),  //用户id
                ygCommentVo.getHaspicture(), //是否有图片，如果为0代表没有图片
                ygCommentVo.getHaspicture() == 0 ? null : ygCommentVo.getPicurls(), //如果为0就传入null,否则就传入urlJson
                ygCommentVo.getStar(),      //五星好评
                new Date(),                 //当前时间
                null,
                1                  //删除逻辑
        );
        //5 调用Mapper层插入
        int config = ygCommentMapper.insComment(ygComment);
        //6 修改Order表
        if(config > 0){
            //评价自增id,订单id，订单编号
            int updInt = updateOrderCommentId(ygComment.getId(),ygCommentVo.getOrderId(),ygCommentVo.getOrderSn());
            //如果修改失败，则删除掉评论表插入的评论，保持数据一致性
            if(updInt != 1){
                ygCommentMapper.deleteById(ygComment.getId());
                config = 0;
            }
        }else{
            config = 0;
        }
        return config;
    }


    /**
     * 根据订单编号修改order表的commentId
     * @param commentId
     * @param orderId
     * @param orderSn
     * @return
     */
    public int updateOrderCommentId(Integer commentId,Integer orderId,String orderSn){
        YgOrder ygOrder = new YgOrder();
        //1 将订单的commentId从-1改为当前新增评论的 自增唯一id
        ygOrder.setCommentid(commentId);
        //2 将订单从“待评价”改为“售后”状态
        ygOrder.setOrderstatus(4);
        //3 修改order表的条件，订单id，订单编号
        ygOrder.setId(orderId);
        ygOrder.setOrdersn(orderSn);
        return ygOrderMapper.updateOrderCommentId(ygOrder);
    }

}